/**
 * @author zhangqiang
 * @date   17/7/20
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import { bindActionCreators } from 'redux'
import {Progress} from '../../components/common/process'
import OrderList from '../../components/payment/index'
import config from '../../config'
import { Toast,Modal} from 'antd-mobile'

import {payMent,weixinQuery} from '../../actions/paymentActions'
import '../../../styles/payment.scss';
import common from '../../utils/common'
import style from './index.scss'

const alert = Modal.alert;

class Payment extends Component {
  constructor(props) {
	  super(props);
		this.state={
		  payType: this.props.payTypes[0], //默认支付类型
			payTypes: [],//支付类型
			data: [],
			chargeOrderId: '',
			isIPhoneHideWX: false
	  }
  }

	toUrl(url) {
      this.context.router.push(url);
  }

	componentWillMount(){
		let checkout_success_data = JSON.parse(sessionStorage.getItem('checkout_success_data')); //下单成功后的信息
		/*
		*  如果是苹果手机隐藏微信支付选项
		* */
		if(common.isIPhone()){
			this.setState({
				isIPhoneHideWX: true
			})
		}
		this.setState({
			data: checkout_success_data
		})

		if(sessionStorage.getItem('payType')){
			this.setState({
				payType: JSON.parse(sessionStorage.getItem('payType'))
			})
		}


	}

  componentDidMount() {
	  common.setViewTitle('订单确认');

	  if(sessionStorage.getItem('weixinPay')){
		  alert('', <div style={{fontSize: '.32rem'}}>请确定微信支付是否已完成</div>, [
			  {
				  text: '已完成支付',
				  onPress: () =>{
					  weixinQuery(sessionStorage.getItem('wxData'),sessionStorage.getItem('forwardUrl'))
					  sessionStorage.removeItem('weixinPay')
					  setTimeout(()=>{
					  	sessionStorage.removeItem('wxData')
					  	sessionStorage.removeItem('forwardUrl')
					  },500)
				  },
				  style: {color: 'red',fontSize: '.3rem'}
			  },
			  { text: '支付遇到问题，重新支付', onPress: () => {
			  	sessionStorage.removeItem('weixinPay')
				  this.orderPay()
		    }, style: {color: '#ababab',fontSize: '.3rem'}},

			  { text: '', onPress: () => console.log('第0个按钮被点击了') ,style:{display: 'none'}},

		  ])
	  }
  }

  componentDidUpdate(){

  }

  componentWillUnmount() {
	  sessionStorage.setItem('getRegionType',1)
  }

	/**
	 * 设置支付类型
	 * @param type 支付类型
	 */
	setPayType(type) {
		sessionStorage.setItem('payType',JSON.stringify(type))
		this.setState({
			payType: type
		})
	}

	//渲染支付方式
	renderPayTypes() {
		let isIPhoneHideWX;
		return this.props.payTypes.map((item, i) => {
				if(this.state.isIPhoneHideWX&&i==1){
					 isIPhoneHideWX = true;
				}
				return <div key={i} className={style.verCenter+' '+'border_bottom_1'} onClick={type => this.setPayType(item)} style={isIPhoneHideWX?{display:'none'}:{}}>
					<img className={style.pay_type_icon} src={item.icon}/>
					<div className={style.title}>{item.title}</div>
					<img className={style.pay_type_select_icon}
					     src={this.state.payType.name == item.name ? './images/select-true.png' : './images/select-false.png'}/>
				</div>
			}
		)
	}

	//渲染订单列表
	renderOrderList(){
		return this.state.data.endorseInfoList.map((item,i)=>{
			return <OrderList data={item} key={i+' '+i+1}/>
		})
	}

	orderPay(){
		let postData = {
			payType: this.state.payType.type,
			objStr: sessionStorage.getItem('pay_data')
		}
		this.props.dispatch(payMent(postData,(res)=>{
			this.setState({
				chargeOrderId: res  //订单号
			})

			// alert(this.state.payType.type)
			if(this.state.payType.type == 2){
				document.getElementById("myform").submit();
			}else if(this.state.payType.type == 3){

			}
		}))
	}

	render() {

		return (
			<div className={style.payment}>

				{/*订单状态-start-*/}
				<Progress/>
				{/*订单状态-end-*/}

				<div className={style.container}>
					{/*订单列表--start*/}
					{this.renderOrderList()}
					{/*订单列表-end-*/}
				</div>

				<div className={style.totaled+' '+'cf'}>
					<span>总计</span>
					<div>
						<span>￥{this.state.data.totalFee/100}</span>
						{/*<img src="./images/icon_right.png" alt=""/>*/}
					</div>
				</div>

				<div className={style.payType}>
					{
						this.renderPayTypes()
					}
				</div>
				<div style={{height: '1.24rem'}}></div>

				<div className={style.pay_button_box}>
						<div className={style.pay_money}>
							<span>总计：</span>
							<span>￥{this.state.data.totalFee/100}</span>
						</div>
					<button className={style.pay_button} onClick={()=>{this.orderPay()}}>立即支付</button>
				</div>

				{
					this.state.payType.type == 2?
						<form  name="myfrom" id="myform" method="post" action={`${config.baseApiUrl}/emsc-partner/b/o/p`} style={{display:'none'}}>
							<input type="text" name="chargeOrderId" value={this.state.chargeOrderId} />
						</form>:null
				}

			</div>
				)
    }
}

//使用context
Payment.contextTypes = {
    router: React.PropTypes.object.isRequired
};

Payment.defaultProps = {
	payTypes: [
		{
			name: 'alipay',
			title: '支付宝支付',
			icon: './images/alipay-icon.png',
			type: '2',
		},
		{
			name: 'weixin',
			title: "微信支付",
			icon: './images/weixin-icon.png',
			type: '3',
		}
	],
};

function mapStateToProps(state) {
	return Object.assign({}, state.homeInfo);
}

export default connect(mapStateToProps)(Payment);
